import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const isLoggedIn = ref(false)

  // 模拟用户数据
  const mockUsers = [
    { 
      id: 1, 
      username: 'user1', 
      name: '张三', 
      avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' 
    },
    { 
      id: 2, 
      username: 'user2', 
      name: '李四', 
      avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png' 
    }
  ]

  const login = (username, password) => {
    // 模拟登录验证
    const foundUser = mockUsers.find(u => u.username === username)
    if (foundUser && password === '123456') {
      user.value = foundUser
      isLoggedIn.value = true
      localStorage.setItem('user', JSON.stringify(foundUser))
      return true
    }
    return false
  }

  const logout = () => {
    user.value = null
    isLoggedIn.value = false
    localStorage.removeItem('user')
  }

  const initAuth = () => {
    const savedUser = localStorage.getItem('user')
    if (savedUser) {
      user.value = JSON.parse(savedUser)
      isLoggedIn.value = true
    }
  }

  return {
    user,
    isLoggedIn,
    login,
    logout,
    initAuth
  }
})
